import HttpMethod from '../constants/http-method-constant';
import LocalGeneralConfig from '../models/local-general-config';
import HttpRequestService from './http-request-service';

/**
 * This service is intend to load the config info from json file in public/assets/config directory.
 * https://create-react-app.dev/docs/using-the-public-folder
 */
export default class ConfigService {
  private static readonly basePath: string = `${import.meta.env.BASE_URL}assets/config`;
  private static localGeneralConfig: LocalGeneralConfig;
  private static loadingConfigPromise: Promise<void> | null;

  static async getLocalGeneralConfig(): Promise<LocalGeneralConfig> {
    // Checks on [localGeneralConfig] to see if need to load config file.
    if (!this.localGeneralConfig) {
      // Checks on [loadingConfigPromise] to see if currently loading is in progress.
      if (!this.loadingConfigPromise) {
        // Creates new promise to load config file.
        this.loadingConfigPromise = new Promise((async (resolve) => {
          try {
            this.localGeneralConfig = await this.loadLocalGeneralConfig() ?? new LocalGeneralConfig();

            return resolve();
          } finally {
            this.loadingConfigPromise = null;
          }
        }));
      }

      // Waits for loading to complete.
      await this.loadingConfigPromise;
    }

    return this.localGeneralConfig;
  }

  /**
   * Loads local general config data.
   */
  private static async loadLocalGeneralConfig(): Promise<LocalGeneralConfig> {
    return (await HttpRequestService.makeOriginalRequest(HttpMethod.get, `${this.basePath}/general-config.json`)).payload;
  }
}